require 'optparse'

$options = {}
parser = OptionParser.new("", 24) do |opts|
  opts.banner = "\nVersion: 1.0 (Jan-2014)\n\n"

  opts.on("-i", "--input INPUT", "Input database file") do |v|
    $options[:input] = v
  end

  opts.on("-o", "--output OUTPUT", "Output CSV file") do |v|
    $options[:output] = v
  end

  opts.on("-l", "--limit N", "number of records") do |v|
    $options[:limit] = v
  end

  opts.on_tail('-h', '--help', 'Displays this help') do
		puts opts, ""
	end
end

begin
  parser.parse!
rescue SystemExit => ex
  exit
rescue Exception => ex
  puts "\nERROR: #{ex.message}\n\nRun ruby to_xls.rb -h for help\n\n"
  exit
end

if $options[:input].nil?
  puts "\nPlease specify the input: -i\n\n"
  exit
end

if $options[:output].nil?
  puts "\nPlease specify the output file: -o\n\n"
  exit
end

$options[:limit] ||= 1000000000
$options[:limit] = $options[:limit].to_i

require 'digest/sha1'
require 'sqlite3'
require 'rubygems'
require 'active_record'
require 'csv'
require 'nokogiri'
require 'zlib'

ActiveRecord::Base.establish_connection(
  :adapter => 'sqlite3',
  :database => $options[:input],
  :timeout => 15000 # You'll only get the BusyException if it takes longer than 15 seconds.
)

class Item < ActiveRecord::Base
end

data = []

Item.limit($options[:limit]).each_with_index do |item, index|
  data << [item.keyword, item.search_url, item.result_count]
end

# headers
headers = ['Keyword', 'Search URL', 'Result Count']
data.insert(0, headers)

CSV.open($options[:output], 'w') do |csv|
  data.each do |line|
    csv << line
  end
end

puts "Done"